/*
 * @Descripttion:
 * @Author: renmingming
 * @Date: 2023-05-18 17:43:43
 * @LastEditors: renmingming
 * @LastEditTime: 2023-09-18 09:53:43
 */

/**
 * 完整解析的静态资源 URL
 * @param {*} url
 * @returns
 */
export const getUrl = (url) => {
	return new URL(`../assets/img/${url}`, import.meta.url).href;
};

/**
 * 过滤特殊字符
 * @param {*} url
 * @returns
 */
export const removeSpecialChars = (str) => {
	const regex = /[`\^。.>？!！￥~!@#$%^&*()=+[\]{}\\|;:'",.<>/?]/g;
	return str.replace(regex, '');
};

/**
 * 工程量表达式输入是否合法
 * @param row
 * @returns {boolean}
 */
export const quantityExpressionHandler = (row) => {
	const errMsg = '计算式输入非法，请重新输入标准四则运算表达式或数值';
	let {
		quantityExpression: value,
		quantityVariableName,
		quantityVariableValue,
	} = row;
	if (!value.length) return [true, '工程量表达式不能为空'];
	const reg = /[^0-9a-zA-Z|\-|\*|\+|\/|\.|(|)]/g;
	if (reg.test(value)) return [true, errMsg];
	let arr = value.match(/[A-Za-z0-9]+(\.\d+)?/g);
  if (arr === null) return [true, errMsg];
	let result = [];
	for (let f of arr) {
		if (isNaN(Number(f))) {
			if (quantityVariableName !== f) return [true, errMsg];
			const reg = new RegExp(`${f}`, 'g');
			console.log('替换：', f, quantityVariableValue);
			value = value.replace(reg, quantityVariableValue);
		}
	}
	try {
		const runResult = new Function(`return ${value}`);
		if (!isFinite(runResult())) return [true, errMsg];
	} catch (error) {
		return [false, ''];
	}
	return [false, ''];
};

/**
 * 纯数字表达式
 * @param {*} value
 * @returns
 */
export const isNumericExpression = (value, varObjMap = null) => {
	const errMsg = '计算式输入非法，请重新输入标准四则运算表达式或数值';
	if (!value.length) return [true, '工程量表达式不能为空'];
	const reg = /[^0-9a-zA-Z|\-|\*|\+|\/|\.|(|)]/g;
	if (reg.test(value)) return [true, errMsg];
	let arr = value.match(/[A-Za-z0-9]+(\.\d+)?/g);
  if (arr === null) return [true, errMsg];
	if (varObjMap) {
		let result = [];
		for (let f of arr) {
			console.log('进入varObjMap');
			const mapVal = varObjMap.get(f.toUpperCase());
			if (isNaN(Number(f))) {
				if (!mapVal) return [true, errMsg];
				const reg = new RegExp(`${f}`, 'g');
				console.log('替换：', f, mapVal.mathFormula);
				value = value.replace(reg, mapVal.mathResult);
			}
		}
	}
	try {
		const runResult = new Function(`return ${value}`);
		if (!isFinite(runResult())) return [true, errMsg];
	} catch (error) {
		return [false, ''];
	}
	return [false, ''];
};

/**
 * 处理表达式的每个数字
 * @param {*} value
 */
export const everyNumericHandler = (value) => {
	if (!value.length) return value;
	let arr = value.split(/-|\+|\*|\/|\(|\)/);
	let result = [];
	arr.forEach((f) => {
		if (f.length && !isNaN(Number(f))) {
			const reg = new RegExp(`${f}`, 'g');
			console.log('替换：', Number(f));
			value = value.replace(
				reg,
				Math.round(Number(f) * 1000000) / 1000000
			);
		}
	});
	return value;
};

/**
 * 价格输入是否合法.
 * @param {string} value
 * @returns {string}
 */
export const removeSpecialCharsFromPrice = (value, fractionDigits = 2) => {
	if (value === null) return value
  const reg = /[^\d\.]/g;
  if (reg.test(value)) {
    return ''
  }
  return Number(Number(value).toFixed(fractionDigits)) || ''
};

/**
 * @description: 下载文件流
 * @param {*} data 文件流
 * @param {*} fileName 文件名
 * @param {*} fileType 文件类型
 * @return {*}
 */
export function downloadFile(
	data,
	fileName = new Date().toString(),
	fileType = 'excel'
) {
	let type = '';
	switch (fileType) {
		case 'excel':
			type =
				'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
			break;
		case 'pdf':
			type = 'application/pdf';
			break;
		default:
			type = 'application/zip';
			break;
	}
	console.log('🚀 获取之后a', data, fileName, fileType);
	const resBlob = new Blob([data]);
	const reader = new FileReader();
	reader.readAsText(resBlob, 'utf-8');
	reader.onload = () => {
		try {
			const result = JSON.parse(reader.result);
			message.error(result.message);
			return '';
		} catch (error) {
			const blob = new Blob([data], { type });
			if ('download' in document.createElement('a')) {
				// 非IE下载
				const elink = document.createElement('a');
				elink.download = fileName;
				elink.style.display = 'none';
				elink.href = window.URL.createObjectURL(blob);
				document.body.appendChild(elink);
				elink.click();
				window.URL.revokeObjectURL(elink.href); // 释放URL 对象
				document.body.removeChild(elink);
			} else {
				// IE10+下载
				if (navigator.msSaveBlob) {
					navigator.msSaveBlob(blob, fileName);
				}
			}
		}
	};
}

/**
 * @description: 下载ysf文件
 * @param {*} data 文件流
 * @param {*} fileName 文件名
 * @param {*} fileType 文件类型
 * @return {*}
 */
export function downloadYsfFile(data, name = new Date().toString()) {
	const resBlob = new Blob([data]);
	const reader = new FileReader();
	reader.readAsText(resBlob, 'utf-8');
	reader.onload = () => {
		try {
			const result = JSON.parse(reader.result);
			message.error(result.message);
			return '';
		} catch (error) {
			const blob = new Blob([data], { type: 'application/octet-stream' });
			const fileName = `${name}.ysf`;
			if ('download' in document.createElement('a')) {
				// 非IE下载
				const elink = document.createElement('a');
				elink.download = fileName;
				elink.style.display = 'none';
				elink.href = window.URL.createObjectURL(blob);
				document.body.appendChild(elink);
				elink.click();
				window.URL.revokeObjectURL(elink.href); // 释放URL 对象
				document.body.removeChild(elink);
			} else {
				// IE10+下载
				if (navigator.msSaveBlob) {
					navigator.msSaveBlob(blob, fileName);
				}
			}
		}
	};
}


export function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * @description: 下载文件
 * @param {*} data 文件
 * @param {*} fileName 文件名
 * @param {*} fileType 文件类型
 * @return {*}
 */
export function downloadFileByUrl (
  data,
  fileName = new Date().toString(),
)  {
  // 非IE下载
  const elink = document.createElement('a')
  elink.download = fileName;
  elink.target = '_blank'
  elink.style.display = 'none';
  elink.href = data;
  elink.click();
}